/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * form.java
 *
 * Created on Sep 20, 2011, 5:00:57 PM
 */
package tampilan;

import inference.Solver;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.Popup;
import jess.Fact;
import jess.JessException;
import jess.awt.TextAreaWriter;
import jess.swing.JTextAreaWriter;

/**
 *
 * @author TOSHIBA
 */
public class form extends javax.swing.JFrame {

    /** Creates new form form */
    public Solver solver = new Solver();

    public form() {
        initComponents();
        //batch disini aja
        solver.batch("knowledge.clp");


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hobby = new javax.swing.JComboBox();
        gender = new javax.swing.JComboBox();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        status = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        submitFacts = new java.awt.Button();
        jLabel8 = new javax.swing.JLabel();
        age = new javax.swing.JComboBox();
        spareTime = new javax.swing.JComboBox();
        budget = new javax.swing.JComboBox();
        hasil = new java.awt.TextArea();
        addRule = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        submitAddRule = new java.awt.Button();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        hobby.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Indoor", "Outdoor" }));

        gender.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "laki-laki", "perempuan" }));
        gender.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                genderActionPerformed(evt);
            }
        });

        jLabel6.setText("Waktu luang");

        jLabel7.setText("Budget");

        status.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "single", "married" }));

        jLabel1.setText("Presento");

        jLabel5.setText("Status");

        jLabel3.setText("Jenis Kelamin");

        jLabel2.setText("Umur (tahun)");

        jLabel4.setText("Hobi");

        submitFacts.setLabel("Kirim");
        submitFacts.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitFactsActionPerformed(evt);
            }
        });

        jLabel8.setText("Hasil :");

        age.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "kurang dari 10", "antara 10 dan 15", "antara 16 dan 20", "lebih dari 20" }));

        spareTime.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "kurang dari 1", "antara 1 sampai 5", "antara 5 sampai 10", "lebih dari 10" }));
        spareTime.setToolTipText("");

        budget.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "kurang dari 100rb", "antara 100rb sampai 500rb", "lebih dari 500rb" }));

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel7))
                                .addGap(38, 38, 38)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(age, 0, 197, Short.MAX_VALUE)
                                    .addComponent(status, 0, 197, Short.MAX_VALUE)
                                    .addComponent(hobby, 0, 197, Short.MAX_VALUE)
                                    .addComponent(submitFacts, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(gender, 0, 197, Short.MAX_VALUE)
                                    .addComponent(spareTime, 0, 197, Short.MAX_VALUE)
                                    .addComponent(budget, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(159, 159, 159))
                    .addComponent(jLabel8))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(31, 31, 31)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(gender, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(hobby, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(spareTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(42, 42, 42)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(budget, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 34, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(submitFacts, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addComponent(jLabel8)))
        );

        addRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addRuleActionPerformed(evt);
            }
        });

        jLabel9.setText("Jika Anda kurang puas, silakan masukkan satu hadiah yang menurut Anda valid :");

        submitAddRule.setLabel("OK");
        submitAddRule.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitAddRuleActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addRule, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
                    .addComponent(hasil, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)
                    .addComponent(submitAddRule, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 390, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21)
                .addComponent(hasil, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(15, 15, 15)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(addRule, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(submitAddRule, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void genderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_genderActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_genderActionPerformed

    private String changeAgeFormat() {
        String selected = this.age.getSelectedItem().toString();
        if (selected.equalsIgnoreCase("kurang dari 10")) {
            return "k10";
        } else if (selected.equalsIgnoreCase("antara 10 dan 15")) {
            return "a1015";
        } else if (selected.equalsIgnoreCase("antara 16 dan 20")) {
            return "a1620";
        } else if (selected.equalsIgnoreCase("lebih dari 20")) {
            return "l20";
        } else {
            return "salah";
        }
    }

    private String changeGenderFormat() {
        String selected = this.gender.getSelectedItem().toString();
        if (selected.equalsIgnoreCase("laki-laki")) {
            return "m";
        } else if (selected.equalsIgnoreCase("perempuan")) {
            return "p";
        } else {
            return "salah";
        }
    }

    private String changespareTimeFormat() {
        String selected = this.spareTime.getSelectedItem().toString();
        if (selected.equalsIgnoreCase("kurang dari 1")) {
            return "k1";
        } else if (selected.equalsIgnoreCase("antara 1 dan 5")) {
            return "a15";
        } else if (selected.equalsIgnoreCase("antara 5 dan 10")) {
            return "a510";
        } else if (selected.equalsIgnoreCase("lebih dari 10")) {
            return "l10";
        } else {
            return "salah";
        }
    }

    private String changeBudgetFormat() {
        String selected = this.budget.getSelectedItem().toString();
        if (selected.equalsIgnoreCase("kurang dari 100rb")) {
            return "k100";
        } else if (selected.equalsIgnoreCase("antara 100rb dan 500rb")) {
            return "a100500";
        } else if (selected.equalsIgnoreCase("lebih dari 500rb")) {
            return "l500";
        } else {
            return "salah";
        }
    }

private void submitFactsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitFactsActionPerformed
    try {
        // TODO add your handling code here:
        //       Iterator<String> it = solver.core.listDefrules();
        //        Arr
        //       for (Iterator<String> it = .iterator(); it.hasNext(); ) {
        //            String s = it.next();  // No downcasting required.
        //            System.out.println(s);
        //        }
        solver.core.reset();
    } catch (JessException ex) {
        Logger.getLogger(form.class.getName()).log(Level.SEVERE, null, ex);
    }
    this.hasil.setText("");

    TextAreaWriter taw = new TextAreaWriter(hasil);


    solver.core.addOutputRouter("t", taw);
    solver.core.addOutputRouter("WSTDOUT", taw);
    solver.core.addOutputRouter("WSTDERR", taw);

    solver.age = this.changeAgeFormat();
    solver.budget = this.changeBudgetFormat();
    solver.gender = this.changeGenderFormat();
    solver.hobby = this.hobby.getSelectedItem().toString();
    solver.spareTime = this.changespareTimeFormat();
    solver.status = this.status.getSelectedItem().toString();


    //solver.addFactsToTemplate();
//            Fact f = solver.core.findFactByID(0);
//                    
//            this.hasil.setText(f.toString());

    solver.exec();
    String s = this.hasil.getText();

    String[] split = s.split(";");

    List lists = solver.getUniqueElements(Arrays.asList(split));
    Collections.sort(lists);
    String print = "";

    for (int i = 0; i < lists.size(); i++) {
        print = print + lists.get(i) + "\n";
    }

    this.hasil.setText(print);

    // Do something interesting, then...
    //System.exit(0);S
    //this.hasil.setText(solver.resulttest);

}//GEN-LAST:event_submitFactsActionPerformed

private void addRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRuleActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_addRuleActionPerformed

    private void generateRule(int number) {
        //number = baca dari file nomor.txt

        //langsung ambil dari form
//    (defrule P8
//	(person (status "married"))
//	=>
//	(printout t "kitchen set;dining set;tea set;"))
        newRule = "\n\n(defrule sys" + number + " (person (age " + "\"" + this.changeAgeFormat() + "\") (gender " + "\"" + this.changeGenderFormat() + "\""
                + ") (status " + "\"" + this.status.getSelectedItem().toString() + "\"))" //person
                + " (activity (spareTime " + "\"" + this.changespareTimeFormat() + "\")" + " (hobby " + "\"" + this.hobby.getSelectedItem().toString() + "\"))"
                + " (present (budget " + "\"" + this.changeBudgetFormat() + "\"))"
                + " => (printout t \"" + this.addRule.getText() + ";\"))";


    }

    private void readNumber() {
        File numberFile = new File("nomor.txt");
        if (numberFile.canRead()) {
            try {
                java.util.Scanner baca = new java.util.Scanner(numberFile);
                //Baca Daleman file
                String number = baca.nextLine();
                this.rulenumber = Integer.parseInt(number);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(form.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    private void incrementNumber() {
        try {
            // Create file 
            FileWriter fstream = new FileWriter("nomor.txt");
            BufferedWriter out = new BufferedWriter(fstream);
            String num = String.valueOf(++this.rulenumber);
            out.write(num);
            //Close the output stream
            out.close();
        } catch (Exception e) {//Catch exception if any
            System.err.println("Error: " + e.getMessage());
        }

    }

private void submitAddRuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitAddRuleActionPerformed
    try {
        File f = new File("knowledge.clp");
        RandomAccessFile raf = new RandomAccessFile(f, "rw");

        raf.seek(f.length());

        this.readNumber();
        this.generateRule(rulenumber);
        //rangkai string defrule, isinya dapet dari dropdown
        raf.writeBytes(newRule);
        //ganti nomor.txt
        this.incrementNumber();
        raf.close();
            try {
                //rete di-reset
                solver.core.reset();
                //batch ulang
                solver.batch("knowledge.clp");
            } catch (JessException ex) {
                Logger.getLogger(form.class.getName()).log(Level.SEVERE, null, ex);
            }
        JOptionPane.showConfirmDialog(this, "Pengetahuan berhasil ditambahkan!");
        this.addRule.setText("");
    } catch (IOException e) {
    }
}//GEN-LAST:event_submitAddRuleActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(form.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new form().setVisible(true);
            }
        });
    }
    private String newRule = "";
    private int rulenumber;
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField addRule;
    private javax.swing.JComboBox age;
    private javax.swing.JComboBox budget;
    private javax.swing.JComboBox gender;
    private java.awt.TextArea hasil;
    private javax.swing.JComboBox hobby;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JComboBox spareTime;
    private javax.swing.JComboBox status;
    private java.awt.Button submitAddRule;
    private java.awt.Button submitFacts;
    // End of variables declaration//GEN-END:variables
}
